#include<iostream>
#include<ctime>
#include<unistd.h>
#include"Socket.hpp"
#include"Protocol.hpp"

using namespace socket_ns;

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        std::cerr<<"enter err\n"<<std::endl;
        exit(0);
    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    SockSPtr sock=std::make_shared<TcpSocket>();
    
    if(!sock->BuildClient(serverip,serverport))
    {
        std::cerr<<"connect error\n"<<std::endl;
    }

    srand(time(nullptr)^getpid());
    const std::string opers="+-*/%!";
    std::string packstreamqueue;
    while(true)
    {
        int x=rand()%10;
        usleep(x*1000);
        int y=rand()%10;
        char oper=opers[y%opers.size()];

        auto req=Factory::BuildRequestDefault();
        req->SetValue(x,y,oper);

        std::string reqstr;
        req->Serialize(&reqstr);
        reqstr=Encode(reqstr);
        sock->Send(reqstr);
        while(true)
        {
            ssize_t n=sock->Recv(&packstreamqueue);
            if(n<=0)
            {
                LOG(INFO,"server %s  quit or recv error\n",serverip.c_str());
                break;
            }
            std::string json=Decode(packstreamqueue);
            if(json.empty())continue;
            
            auto resp=Factory::BuildResponseDefault();
            resp->DeSerialize(json);
            resp->PrintfResult();
            break;
        }
        sleep(3);
    }

    sock->Close();
    return 0;
}
